using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using HappySprite;
using HappySprite.Simulation;

namespace HappyInvaders
{
    abstract class Entity
    {
        public event GenericEventHandler<Vector2> PositionChanged;
        public event GenericEventHandler Removed;
        public event GenericEventHandler<BitArray> TextureChanged;

        Model owner;
        Body item = new Body();
        bool positionCurrent;

        public Entity()
        {
            Item.Tag = this;
        }

        public Vector2 Position
        {
            get 
            { 
                return item.Transform.Position; 
            }
            set 
            {
                positionCurrent = false;
                item.Transform.Position = value; 
            }
        }

        protected virtual bool ShouldUpdate
        {
            get { return true; }
        }

        protected bool PositionCurrent
        {
            get { return positionCurrent; }
            set { positionCurrent = value; }
        }

        internal Body Item
        {
            get { return item; }
        }

        internal Model Owner
        {
            get { return owner; }
            set { owner = value; }
        }

        internal virtual void OnAdd()
        {
        }

        internal virtual void OnRemove()
        {
        }

        protected virtual void OnPositionChanged(Vector2 position)
        {
            if (PositionChanged != null)
            {
                PositionChanged(position);
            }
        }

        protected virtual void OnRemoved()
        {
            if (Removed != null)
            {
                Removed();
            }
        }

        protected virtual void OnTextureChanged(BitArray bitArray)
        {
            if (TextureChanged != null)
            {
                TextureChanged(bitArray);
            }
        }

        public virtual void Update()
        {
            if (ShouldUpdate)
            {
                OnPositionChanged(item.Transform.Position);
                positionCurrent = true;
            }
        }

        public void Remove()
        {
            OnRemove();

            Owner.RemoveEntity(this);

            if (Item.Owner != null)
            {
                Item.Owner.Remove(item);
            }

            OnRemoved();

            PositionChanged = null;
            Removed = null;
            TextureChanged = null;

            Global.RecycleBin.Recycle(this);
        }
    }
}
